package com.longshine.downcomp;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import com.longshine.log.Log;
import com.longshine.tools.util.CommonUtil;
import com.longshine.tools.util.NumberUtil;

public class EquipConnection extends Thread {

	private Socket socket;
	private String ip;
	private int port;
	private DataInputStream inStream;
	private DataOutputStream outStream;
	private boolean isConnected = false;
	
	public EquipConnection(String ip,int port){
		this.ip = ip;
		this.port = port;
	}
	
	public boolean isConnected(){
		return this.isConnected;
	}
	
	public void run(){
		while(true){
			//断开 了，连接
			while(!isConnected){
				try {
					startConn();
				} catch (Exception e) {
					stopConn();
					break;
				}
				CommonUtil.delay(2000L);
			}
			CommonUtil.delay(2000L);
		}
	}
	
	public void startService(){
		start();
	}
	
	public void stopConn(){
		if(isConnected)
			Log.println("断开 连接:"+ip+","+port);
		try{
			isConnected = false;
			if(inStream != null){
				inStream.close();
				inStream = null;
			}
			if(outStream != null){
				outStream.close();
				outStream = null;
			}
			if(socket != null){
				socket.close();
				socket = null;
			}
		}
		catch(Exception e){
			
		}
	}
	
	private void startConn() throws Exception{
		Log.println("开始连接:"+ip+","+port);
		socket = new Socket(ip,port);
		inStream = new DataInputStream(socket.getInputStream());
		outStream = new DataOutputStream(socket.getOutputStream());
		isConnected = true;
		Log.println("连接:"+ip+","+port+"成功");
	}
	
	public void sendStr(String str) throws Exception{
		synchronized(this){
			try {
				outStream.write(NumberUtil.str2ByteArr(str));
				Log.logSendComm(str);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public String recvStr() throws Exception{
        byte [] buf = new byte[100];
        try {
            int lent = inStream.read(buf);
            String ret = NumberUtil.toHexStr(buf,lent);
            ret = ret.toUpperCase();
            Log.logRecvComm(ret);
            return ret;
        } catch (IOException e) {
                throw e;
        }
	}
	

}
